package Network;

import java.util.LinkedList;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import Context.Constant;
import Context.ContextHolder;
import Data.SendingMessage;
import Utility.LogContext;
import Utility.LogManager;

public class SendingMessageQueue {
	private Semaphore emptySemaphore;

    private Semaphore fullSemaphore;
    
    private LinkedList<SendingMessage> msgSendingQueue;
    
    private Lock msgSendingLock;
    
    public SendingMessageQueue() {
    	LogManager.getSingletonManager().writeLog(
    			"Begin initializing the sending message queue", LogContext.LOG_INFO);
    	try {
    		int maxReceivingLength = Integer.parseInt(
    				ContextHolder.getContext().getProperty(Constant.MAX_MSGRECEIVING_QUEUE));
    		System.out.println(maxReceivingLength);
    		emptySemaphore = new Semaphore(maxReceivingLength);
    		fullSemaphore = new Semaphore(0);
    		msgSendingQueue = new LinkedList<SendingMessage>();
    		msgSendingLock = new ReentrantLock();
    	}
    	catch (NumberFormatException e) {
			// TODO: handle exception
    		e.printStackTrace();
		}
    	LogManager.getSingletonManager().writeLog(
    			"End initializing the receiving message queue", LogContext.LOG_INFO);
    }
    
    public void pushSendingMessage(SendingMessage message){
    	try {
	    	emptySemaphore.acquire();
	    	msgSendingLock.lock();
	    	msgSendingQueue.add(message);
	    	msgSendingLock.unlock();
	    	fullSemaphore.release();
	    } catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
    }
    public SendingMessage pollReceivedMessage(){
    	SendingMessage message = null;
    	try {
	    	fullSemaphore.acquire();
	    	msgSendingLock.lock();
	        message = msgSendingQueue.removeFirst();
	        msgSendingLock.unlock();
	        emptySemaphore.release();
	    } catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return message;
    }
}
